package com.taokatao.cardmee.business;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.WebLayout;
import com.taokatao.cardmee.api.security.ServiceUrlProvider;
import com.taokatao.cardmee.business.login.LoginActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class MoreLayout extends LinearLayout {
    @BindView(R.id.v_fit) View vFit;
    @BindView(R.id.l_web) WebLayout lWeb;

    private boolean hasFirstOpened;
    private String mOpenRootPage;

    public MoreLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        ButterKnife.bind(this, LayoutInflater.from(context).inflate(R.layout.layout_more, this));

        lWeb.setOpenNewPage(true);

        Utils.fitSysWindowAndSetStatusBarMode(0xFFFFFFFF, vFit);
    }

    public void loadRootPageJustFirstTime() {
        mOpenRootPage = ServiceUrlProvider.obtainMoreUrl();
        if (TextUtils.isEmpty(mOpenRootPage)) {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            getContext().startActivity(intent);
        } else {
            removeCallbacks(runLoadRoot);
            postDelayed(runLoadRoot, C.settings.ANIMATION_TIME);
        }
    }

    // 切换用户需要强行刷新首页Url，因为Url中携带用户信息
    public void loadRootPageMandatory() {
        Utils.loge("MoreLayout loadRootPageMandatory ACTION_USER_SWITCH");
        final String currRootPage = ServiceUrlProvider.obtainMoreUrl();
        if (!TextUtils.equals(mOpenRootPage, currRootPage)) {
            lWeb.loadUrl(mOpenRootPage = currRootPage);
        }
    }

    private final Runnable runLoadRoot = new Runnable() {
        @Override
        public void run() {
            if (!hasFirstOpened) {
                lWeb.loadUrl(mOpenRootPage);
                hasFirstOpened = true;
            }
        }
    };

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isInEditMode()) return;
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(BusEvent event) {
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.USER_PROFILE_INFO_CHANGED:
                case BusEvent.ACTION_USER_SWITCH:
                    loadRootPageMandatory();
                    break;
            }
        }
    }
}
